package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.controller.vo.ShowInfoVo;
import com.hunttown.mes.manage.service.AnalysisCatalogManageService;
import com.hunttown.mes.manage.service.MesEquipmentManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportCompanyManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.mes.rpc.domain.MesEquipmentDTO;
import com.hunttown.mes.rpc.domain.TransportCompanyDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisVisualCatalogDTOQuery;
import com.hunttown.mes.rpc.domain.query.MesEquipmentDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-03-30 15:24:50
 */
@Controller
@RequestMapping(value = "/mes/equipment")
public class MesEquipmentController {

    private final static Logger logger = LoggerFactory.getLogger(MesEquipmentController.class);

    private final MesEquipmentManageService mesEquipmentService;
    private final AnalysisManageManageService manageService;
    private final AnalysisCatalogManageService catalogService;
    private final TransportCompanyManageService companyService;
    private final ModelService modelService;

    @Autowired
    public MesEquipmentController(MesEquipmentManageService mesEquipmentService, AnalysisManageManageService manageService, AnalysisCatalogManageService catalogService, TransportCompanyManageService companyService, ModelService modelService) {
        this.mesEquipmentService = mesEquipmentService;
        this.manageService = manageService;
        this.catalogService = catalogService;
        this.companyService = companyService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, MesEquipmentDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<MesEquipmentDTO> dataPage = mesEquipmentService.getForPage(dtoQuery);

        for (MesEquipmentDTO item : dataPage.getItems()) {
            item.setEquipCateName(modelService.getCatalogName(item.getEquipCate()));
            item.setBrandName(modelService.getCatalogName(item.getBrandId()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"J-S-SBXX-BJ", "J-S-SBXX-SC", "J-S-SBXX-QTY"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "mes/equipment/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        MesEquipmentDTO obj;

        if (id > 0) {
            obj = mesEquipmentService.getById(id);
        } else {
            obj = new MesEquipmentDTO();
            obj.setId(0);
            obj.setProductionDate(new Date());
            obj.setOperationDate(new Date());
            obj.setStatus(1);
        }
        model.addAttribute("Obj", obj);

        //设备品牌
        modelService.getCatalogListForRecursion(model, 24, "equipBrandList");

        //设备类型
        modelService.getCatalogListForRecursion(model, 31, "equipCateList");

        //生产厂家
        modelService.getCompayPage(model, 8);

        return "mes/equipment/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, MesEquipmentDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                MesEquipmentDTOQuery query = new MesEquipmentDTOQuery();
                query.setEquipCode(objDTO.getEquipCode());
                MesEquipmentDTO obj = mesEquipmentService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此设备编码已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            if (objDTO.getCarId() == null) {
                objDTO.setCarId(0);
            }
            if (objDTO.getDriverId() == null) {
                objDTO.setDriverId(0);
            }

            //日期
            objDTO.setOperationDate(DateConvertUtils.strToDate(objDTO.getOperationDateSr()));
            objDTO.setProductionDate(DateConvertUtils.strToDate(objDTO.getProductionDateSr()));

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO.setServiceLife(0);
                objDTO.setCurrStatus(1);
                objDTO.setTotalMinutes(0);
                objDTO.setChargeId(0);
                objDTO = mesEquipmentService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = mesEquipmentService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = mesEquipmentService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = mesEquipmentService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        MesEquipmentDTO obj = new MesEquipmentDTO();
        obj.setId(id);

        if (id > 0) {
            obj = mesEquipmentService.getById(id);
        }
        mesEquipmentService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //详情
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public String getInfo(Model model, Integer id) {

        //显示标题
        String showTitle = "未知";

        //数据
        ShowInfoVo vo;
        List<ShowInfoVo> dataList = new ArrayList<>();

        if (id != null && id > 0) {
            MesEquipmentDTO obj = mesEquipmentService.getById(id);

            if (obj != null) {
                showTitle = obj.getEquipName();

                vo = new ShowInfoVo();
                vo.setKey("编号ID");
                vo.setValue(obj.getId());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备名称");
                vo.setValue(obj.getEquipName());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备编码");
                vo.setValue(obj.getEquipCode());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备类型");
                vo.setValue(modelService.getCatalogName(obj.getEquipCate()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备品牌");
                vo.setValue(modelService.getCatalogName(obj.getBrandId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备型号");
                vo.setValue(obj.getModel());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备版本");
                vo.setValue(obj.getEquipVer());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("生产厂家");
                vo.setValue(modelService.getCompanyName(obj.getManufacturerId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("出厂日期");
                vo.setValue(obj.getProductionDateSr());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("安装位置");
                vo.setValue(obj.getPosition());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备状态");
                vo.setValue("");
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("备注说明");
                vo.setValue(obj.getRemark());
                dataList.add(vo);
            }

            model.addAttribute("showTitle", showTitle);
            model.addAttribute("dataList", dataList);
        }

        return "show/getinfo-template";
    }

    //endregion

    //region 获取关联设备

    /**
     * 获取关联设备
     *
     * @param model    model
     * @param equipIds 已关联的ID集合
     * @return model
     */
    @RequestMapping(value = "/getEquipmentList", method = RequestMethod.POST)
    public String getEquipmentList(Model model, String equipIds) {

        //处理equipIds
        List<Integer> idList = FormatUtils.commaToList_Integer(equipIds);

        MesEquipmentDTOQuery query = new MesEquipmentDTOQuery();
        query.setPageSize(1000);
        query.setStopFlag(0);
        Page<MesEquipmentDTO> dataPage = mesEquipmentService.getForPage(query);

        for (MesEquipmentDTO item : dataPage.getItems()) {
            if (idList.contains(item.getId())) {
                item.setIsSelect(1);
            }
        }

        model.addAttribute("page", dataPage);

        return "mes/equipment/equipment-list-modal";
    }
    //endregion

}